package dk.ucn.datamatiker.saveme;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import android.util.Log;

public class TaxiDetailsFetcher implements Runnable {
	private static final String URL_GET_ESTIMATE_AND_PLATE_NUMBER =
			"http://balder.ucn.dk/dm77_gr2/SaveMe.svc/GetEstimatedTimeAndPlateNr/";
	private String[] response;
	private int requestId;

	public TaxiDetailsFetcher(int id) {
		requestId = id;
	}

	public void run() {
		InputStream is;
		try {
			URL theURL = new URL(URL_GET_ESTIMATE_AND_PLATE_NUMBER + requestId);
			is = theURL.openConnection().getInputStream();
			response = parse(is);
		} catch (IOException ioException) {
			Log.e("TaxiDetailsFether", "run()", ioException);
		}
	}

	private String[] parse(InputStream inputStream) {
		List<String> list = new ArrayList<String>();
		String[] returnResult = null;
		boolean found = false;
		try {
			XmlPullParserFactory parserFactory = XmlPullParserFactory.newInstance();
			parserFactory.setNamespaceAware(true);
			XmlPullParser xmlParser = parserFactory.newPullParser();
			xmlParser.setInput(inputStream, null);

			while (xmlParser.getEventType() != XmlPullParser.END_DOCUMENT && !found) {
				if (xmlParser.getEventType() == XmlPullParser.START_TAG) {
					String theTag = xmlParser.getName();

					if (theTag.equals("estimatedTime")
							&& xmlParser.getEventType() != XmlPullParser.END_TAG) {
						list.add(xmlParser.nextText());
					} else if (theTag.equals("plateNr")
							&& xmlParser.getEventType() != XmlPullParser.END_TAG) {
						list.add(xmlParser.nextText());
					}
				}
				xmlParser.next();
			}
			returnResult = list.toArray(new String[list.size()]);
		} catch (XmlPullParserException xmlPullParserException) {
			Log.e("TaxiDetailsFether", "parse", xmlPullParserException);
		} catch (IOException ioException) {
			Log.e("TaxiDetailsFether", "parse", ioException);
		}
		return returnResult;
	}

	public String[] getResponse() {
		return response;
	}
}